package cn.johnyu;

import cn.johnyu.model.DataModel;
import com.google.gson.Gson;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xcontent.XContentType;

import java.io.IOException;

public class ElasticsearchGsonDemo {

    public static void main(String[] args) {
        try (RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")))) {

            Gson gson = new Gson();

            // 索引 10 条记录
            for (int i = 1; i <= 10; i++) {
                DataModel data = new DataModel("Title " + i, "Content for record " + i);
                String jsonString = gson.toJson(data);

                IndexRequest request = new IndexRequest("my_index2")
                        .id(String.valueOf(i))
                        .source(jsonString, XContentType.JSON);
                client.index(request, RequestOptions.DEFAULT);
            }

            // 执行全文搜索
            SearchRequest searchRequest = new SearchRequest("my_index2");
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//            searchSourceBuilder.query(QueryBuilders.matchQuery("content", "3 OR 4"));
            searchSourceBuilder.query(QueryBuilders.matchAllQuery());
            searchRequest.source(searchSourceBuilder);

            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            System.out.println("Search Response: " + searchResponse);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
